import React, { useState, useEffect, useRef } from 'react'
import Header from '../components/Header'
import UploadArea from '../components/UploadArea'
import { detectAndSaveImage, listImages, deleteImage } from '../utils/mockApi'
import '../styles/theme.css'
import '../styles/backgrounds.css'
import './DefectDetect.css'

function fileToDataUrl(file){
  return new Promise((res, rej) => {
    const fr = new FileReader()
    fr.onload = ()=>res(fr.result)
    fr.onerror = e=>rej(e)
    fr.readAsDataURL(file)
  })
}

export default function DefectDetect(){
  const [list, setList] = useState([])
  const [loading, setLoading] = useState(false)
  const [detecting, setDetecting] = useState(false)
  const [progress, setProgress] = useState(0)
  const stopRequestedRef = useRef(false)
  const [modalItem, setModalItem] = useState(null)
  const [currentItem, setCurrentItem] = useState(null)
  const [cameraOpen, setCameraOpen] = useState(false)
  const [detectionStats, setDetectionStats] = useState({ total: 0, defects: 0, avgConfidence: 0 })
  
  const videoRef = useRef(null)
  const streamRef = useRef(null)
  const videoInputRef = useRef(null)
  const folderInputRef = useRef(null)

  useEffect(()=>{ 
    async function init() {
      await load()
    }
    init()
  }, [])

  async function load(){
    const items = await listImages()
    setList(items || [])
  }

  useEffect(() => {
    if (currentItem && currentItem.detections) {
      const detections = Array.isArray(currentItem.detections) ? currentItem.detections : [currentItem.detections]
      const total = detections.length
      const defects = detections.filter(d => d && (d.confidence ?? d.score ?? 0) > 0.5).length
      const avgConf = total > 0 ? detections.reduce((sum, d) => sum + (d.confidence ?? d.score ?? 0), 0) / total : 0
      setDetectionStats({ total, defects, avgConfidence: avgConf })
    } else {
      setDetectionStats({ total: 0, defects: 0, avgConfidence: 0 })
    }
  }, [currentItem])

  async function handleFiles(files){
    if (!files || files.length === 0) return
    setLoading(true)
    setProgress(0)
    try{
      for (let i = 0; i < files.length; i++) {
        const f = files[i]
        if (!f || (f.type && !f.type.startsWith('image/'))) continue
        try{
          const dataUrl = await fileToDataUrl(f)
          const saved = await detectAndSaveImage({ name: f.name, dataUrl })
          setCurrentItem(saved)
          setProgress(Math.round(((i + 1) / files.length) * 100))
          await new Promise(r => setTimeout(r, 250))
        }catch(err){
          console.error('文件处理失败', err)
        }
      }
    }finally{
      setLoading(false)
      setProgress(0)
    }
  }

  function handleLoadVideoClick(){ if (videoInputRef.current) videoInputRef.current.click() }

  async function onVideoSelected(e){
    const file = e.target.files && e.target.files[0]
    if (!file) return
    const url = URL.createObjectURL(file)
    const vid = document.createElement('video')
    vid.src = url; vid.muted = true; vid.playsInline = true
    await vid.play().catch(err => console.warn('video play rejected:', err))
    await new Promise(res => {
      if (vid.readyState >= 2) return res()
      vid.onloadeddata = ()=>res()
      setTimeout(res, 1000)
    })
    const canvas = document.createElement('canvas')
    canvas.width = vid.videoWidth || 640; canvas.height = vid.videoHeight || 480
    const ctx = canvas.getContext('2d')
    ctx.drawImage(vid, 0, 0, canvas.width, canvas.height)
    const dataUrl = canvas.toDataURL('image/jpeg')
    URL.revokeObjectURL(url)

    setLoading(true)
    try{
      const saved = await detectAndSaveImage({ name: file.name + '_frame1.jpg', dataUrl })
      setCurrentItem(saved)
    }catch(err){
      console.error('视频帧检测失败', err)
    }
    setLoading(false)
    e.target.value = ''
  }

  async function handleOpenCamera(){
    if (cameraOpen){ stopCamera(); return }
    try{
      const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false })
      streamRef.current = stream
      if (videoRef.current) { videoRef.current.srcObject = stream; videoRef.current.play().catch(()=>{}) }
      setCameraOpen(true)
    }catch(err){
      console.error('无法打开摄像头', err)
      alert('无法打开摄像头：' + (err.message || err))
    }
  }

  function stopCamera(){
    try{
      if (streamRef.current){ streamRef.current.getTracks().forEach(t=>t.stop()); streamRef.current = null }
      if (videoRef.current){ videoRef.current.pause(); videoRef.current.srcObject = null }
    }catch(err){ console.warn(err) }
    setCameraOpen(false)
  }

  async function handleCaptureAndDetect(){
    if (!videoRef.current) return
    const vid = videoRef.current
    const w = vid.videoWidth || 640; const h = vid.videoHeight || 480
    const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h
    const ctx = canvas.getContext('2d'); ctx.drawImage(vid, 0, 0, w, h)
    const dataUrl = canvas.toDataURL('image/jpeg')
    setLoading(true)
    try{
      const saved = await detectAndSaveImage({ name: `camera_${Date.now()}.jpg`, dataUrl })
      setCurrentItem(saved)
    }catch(err){
      console.error('拍照检测失败', err)
    }
    setLoading(false)
  }

  function handleLoadFolderClick(){ if (folderInputRef.current) folderInputRef.current.click() }

  async function onFolderSelected(e){
    const files = Array.from(e.target.files || [])
    const images = files.filter(f => f.type && f.type.startsWith('image/'))
    await handleFiles(images)
    e.target.value = ''
  }

  async function handleStartDetect(){
    if ((!list || list.length === 0) && !currentItem){ alert('当前没有图片可检测'); return }
    stopRequestedRef.current = false
    setDetecting(true)
    setProgress(0)
    try{
      if (list && list.length > 0){
        for (let i=0;i<list.length;i++){
          if (stopRequestedRef.current) break
          const it = list[i]
          const dataUrl = it.dataUrl || it.url || it.src
          if (!dataUrl) continue
          try{
            const saved = await detectAndSaveImage({ name: it.name || `img_${i}`, dataUrl })
            setCurrentItem(saved)
            setProgress(Math.round(((i + 1) / list.length) * 100))
            setList(prev => {
              const copy = [...prev]
              const idx = copy.findIndex(x => x.id === it.id)
              if (idx !== -1) copy[idx] = saved
              return copy
            })
          }catch(err){
            console.error('单张检测失败', err)
          }
        }
      } else if (currentItem){
        const dataUrl = currentItem.dataUrl || currentItem.url || currentItem.src
        if (dataUrl){
          const saved = await detectAndSaveImage({ name: currentItem.name || `img_current_${Date.now()}.jpg`, dataUrl })
          setCurrentItem(saved)
          setProgress(100)
        }
      }
    }catch(err){
      console.error('批量检测失败', err)
    }finally{
      stopRequestedRef.current = false
      setDetecting(false)
      setProgress(0)
    }
  }

  function handleStopDetect(){
    if (!detecting) return
    stopRequestedRef.current = true
    setDetecting(false)
  }

  async function handleRemove(id){
    if (!id) return
    if (!window.confirm('确认删除？此操作不可恢复（仅演示）')) return
    try{
      const res = await deleteImage(id)
      if (res && res.ok) {
        if (currentItem && (currentItem.id === id || currentItem === id)) setCurrentItem(null)
        setList(prev => prev.filter(it => it.id !== id))
      } else {
        alert('删除失败：' + (res && res.reason ? res.reason : '未知错误'))
      }
    }catch(err){
      console.error('删除失败', err)
      alert('删除失败：' + (err.message || err))
    }
  }

  function openModal(item){ setModalItem(item) }
  function closeModal(){ setModalItem(null) }

  async function handleSaveResults(){
    if (!currentItem) { alert('当前没有检测到可保存的图片'); return }
    try{
      setLoading(true)
      if (!currentItem.id) {
        await detectAndSaveImage({ name: currentItem.name || `saved_${Date.now()}.jpg`, dataUrl: currentItem.dataUrl || currentItem.url || currentItem.src })
      }
      window.location.href = '/data'
    }catch(err){
      console.error('保存失败', err)
      alert('保存失败：' + (err.message || err))
    }finally{
      setLoading(false)
    }
  }

  const currentDetections = currentItem && currentItem.detections
    ? (Array.isArray(currentItem.detections) ? currentItem.detections : [currentItem.detections])
    : []

  return (
    <>
      <div className="site-bg bg-core" aria-hidden="true" />

      <div className="page-bg">
        <Header />
        <div className="container page">
          {/* 页面标题 */}
          <div className="page-header-detect">
            <div>
              <h2 className="page-title">智能缺陷检测</h2>
            </div>
            {currentItem && (
              <div className="detection-stats-row">
                <div className="stat-card">
                  <div className="stat-icon">🎯</div>
                  <div className="stat-content">
                    <div className="stat-value">{detectionStats.total}</div>
                    <div className="stat-label">检测到缺陷</div>
                  </div>
                </div>
                <div className="stat-card">
                  <div className="stat-icon">⚠️</div>
                  <div className="stat-content">
                    <div className="stat-value">{detectionStats.defects}</div>
                    <div className="stat-label">高置信度</div>
                  </div>
                </div>
                <div className="stat-card">
                  <div className="stat-icon">📊</div>
                  <div className="stat-content">
                    <div className="stat-value">{(detectionStats.avgConfidence * 100).toFixed(1)}%</div>
                    <div className="stat-label">平均置信度</div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* 进度条 */}
          {(loading || detecting) && progress > 0 && (
            <div className="progress-container">
              <div className="progress-bar">
                <div className="progress-fill" style={{ width: `${progress}%` }}></div>
              </div>
              <span className="progress-text">{progress}%</span>
            </div>
          )}

          <div className="detect-layout">
            {/* 左侧控制面板 */}
            <aside className="control-panel">
              <div className="card control-card">
                <div className="control-header">
                  <span className="control-icon">🎯</span>
                  <h3>模型选择</h3>
                </div>
                <div className="control-content">
                  <select className="model-select">
                    <option>YOLOv11n (快速)</option>
                    <option>YOLOv11s (标准)</option>
                    <option>YOLOv11m (高精度)</option>
                  </select>
                  <button className="btn secondary full">
                    <span>⚙️</span> 加载模型
                  </button>
                </div>
              </div>

              <div className="card control-card">
                <div className="control-header">
                  <span className="control-icon">📤</span>
                  <h3>输入源</h3>
                </div>
                <div className="control-content">
                  <UploadArea onFiles={handleFiles} />
                  <div className="input-buttons">
                    <button className="btn ghost full" onClick={handleLoadVideoClick} disabled={loading}>
                      <span>🎬</span> 视频
                    </button>
                    <button className="btn ghost full" onClick={handleOpenCamera} disabled={loading}>
                      <span>📷</span> {cameraOpen ? '关闭' : '摄像头'}
                    </button>
                    <button className="btn ghost full" onClick={handleLoadFolderClick} disabled={loading}>
                      <span>📁</span> 文件夹
                    </button>
                  </div>
                </div>
              </div>

              <div className="card control-card">
                <div className="control-header">
                  <span className="control-icon">⚡</span>
                  <h3>操作</h3>
                </div>
                <div className="control-content action-buttons">
                  <button 
                    className="btn primary full" 
                    onClick={handleStartDetect} 
                    disabled={detecting || (!currentItem && (!list || list.length===0))}
                  >
                    {detecting ? (
                      <><span className="loading"></span> 检测中...</>
                    ) : (
                      <><span>🔍</span> 开始检测</>
                    )}
                  </button>
                  <button 
                    className="btn danger full" 
                    onClick={handleStopDetect} 
                    disabled={!detecting}
                  >
                    <span>⏹️</span> 停止
                  </button>
                  <button 
                    className="btn success full" 
                    onClick={handleSaveResults} 
                    disabled={!currentItem || loading}
                  >
                    <span>💾</span> 保存结果
                  </button>
                </div>
              </div>
            </aside>

            {/* 主检测区域 */}
            <main className="detection-main">
              <div className="card detection-viewer">
                <div className="viewer-header">
                  <h3>
                    <span className="viewer-icon">👁️</span>
                    实时检测视图
                  </h3>
                  <div className="viewer-actions">
                    <button className="btn-icon" onClick={()=>{ setCurrentItem(null) }} title="清空">
                      🗑️
                    </button>
                    <button className="btn-icon" onClick={async ()=>{ await load() }} title="刷新">
                      🔄
                    </button>
                  </div>
                </div>

                <div className="viewer-content">
                  {currentItem ? (
                    <>
                      <div className="image-display">
                        <img src={currentItem.dataUrl || currentItem.url || currentItem.src} alt={currentItem.name} />
                        {currentDetections.slice(0,5).map((d,i)=>{
                          const bbox = d && (d.bbox || (d.xmin != null ? [d.xmin,d.ymin,d.xmax,d.ymax] : null))
                          if (!bbox) return null
                          const style = { 
                            left: `${6 + i*6}%`, 
                            top: `${6 + i*6}%`, 
                            width:'30%', 
                            height:'18%', 
                            border:'3px solid #ef4444',
                            boxShadow: '0 0 12px rgba(239, 68, 68, 0.5)',
                            position:'absolute',
                            borderRadius: '4px',
                            animation: 'bboxPulse 2s ease-in-out infinite'
                          }
                          return <div key={i} className="bbox" style={style}></div>
                        })}
                      </div>

                      <div className="image-info-bar">
                        <div className="image-name">
                          <span className="file-icon">📄</span>
                          {currentItem.name || '当前图片'}
                        </div>
                        <div className="image-actions">
                          <button className="btn sm ghost" onClick={()=>openModal(currentItem)}>
                            🔍 查看大图
                          </button>
                          {currentItem.id && (
                            <button className="btn sm ghost" onClick={()=>handleRemove(currentItem.id)}>
                              🗑️ 删除
                            </button>
                          )}
                        </div>
                      </div>
                    </>
                  ) : (
                    <div className="empty-viewer">
                      <div className="empty-icon">📸</div>
                      <h3>准备开始检测</h3>
                      <p>拖拽图片到上传区域，或使用左侧输入源选项</p>
                    </div>
                  )}
                </div>
              </div>

              {/* 摄像头预览 */}
              {cameraOpen && (
                <div className="card camera-preview">
                  <div className="camera-container">
                    <video ref={videoRef} autoPlay muted playsInline className="camera-video" />
                    <div className="camera-controls">
                      <button className="btn primary" onClick={handleCaptureAndDetect}>
                        📷 拍照并检测
                      </button>
                      <button className="btn ghost" onClick={stopCamera}>
                        ❌ 关闭
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {/* 检测结果表格 */}
              <div className="card results-card">
                <div className="results-header">
                  <h3>
                    <span className="results-icon">📋</span>
                    检测结果详情
                  </h3>
                  <div className="results-badge">
                    {currentDetections.length} 个缺陷
                  </div>
                </div>

                <div className="results-table-container">
                  <table className="results-table">
                    <thead>
                      <tr>
                        <th>序号</th>
                        <th>类别</th>
                        <th>置信度</th>
                        <th>位置坐标</th>
                        <th>风险等级</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(!currentDetections || currentDetections.length === 0) ? (
                        <tr>
                          <td colSpan="5" className="empty-cell">
                            <div className="empty-table">
                              <span>📭</span>
                              <p>暂无检测结果</p>
                            </div>
                          </td>
                        </tr>
                      ) : (
                        currentDetections.map((d, idx) => {
                          const cls = d ? (d.class || d.label || d.name) : ''
                          const score = d ? (d.confidence ?? d.score ?? 0) : 0
                          const bbox = d && (d.bbox ? d.bbox : (d.xmin!=null ? [d.xmin,d.ymin,d.xmax,d.ymax] : null))
                          const riskLevel = score >= 0.8 ? '高' : score >= 0.5 ? '中' : '低'
                          const riskClass = score >= 0.8 ? 'risk-high' : score >= 0.5 ? 'risk-medium' : 'risk-low'
                          
                          return (
                            <tr key={idx} className="result-row">
                              <td className="row-index">{idx+1}</td>
                              <td className="row-class">
                                <span className="class-badge">{cls}</span>
                              </td>
                              <td className="row-confidence">
                                <div className="confidence-bar-container">
                                  <div className="confidence-bar" style={{width: `${score * 100}%`}}></div>
                                  <span className="confidence-text">{(score * 100).toFixed(1)}%</span>
                                </div>
                              </td>
                              <td className="row-bbox">
                                {bbox ? (Array.isArray(bbox) ? `(${bbox.map(n => n.toFixed(0)).join(',')})` : JSON.stringify(bbox)) : '—'}
                              </td>
                              <td className="row-risk">
                                <span className={`risk-badge ${riskClass}`}>{riskLevel}</span>
                              </td>
                            </tr>
                          )
                        })
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </main>
          </div>
        </div>

        <input ref={videoInputRef} type="file" accept="video/*" style={{display:'none'}} onChange={onVideoSelected} />
        <input ref={folderInputRef} type="file" webkitdirectory="true" directory="true" multiple style={{display:'none'}} onChange={onFolderSelected} />

        {modalItem && (
          <div className="modal-backdrop" onClick={closeModal}>
            <div className="modal-content" onClick={(e)=>e.stopPropagation()}>
              <div className="modal-header">
                <h3>{modalItem.name || '图片详情'}</h3>
                <button className="btn-close" onClick={closeModal}>✕</button>
              </div>

              <div className="modal-body">
                <div className="modal-image-wrap">
                  <img src={modalItem.dataUrl || modalItem.url || modalItem.src} alt={modalItem.name} />
                  {(modalItem.detections || []).slice(0,5).map((d,i)=>{
                    const bbox = d && (d.bbox || (d.xmin != null ? [d.xmin,d.ymin,d.xmax,d.ymax] : null))
                    if (!bbox) return null
                    const style = { 
                      left: `${8 + i*6}%`, 
                      top: `${6 + i*6}%`, 
                      width:'30%', 
                      height:'18%', 
                      border:'3px solid #ef4444',
                      position:'absolute',
                      borderRadius: '4px',
                      boxShadow: '0 0 12px rgba(239, 68, 68, 0.5)'
                    }
                    return <div key={i} className="bbox" style={style}></div>
                  })}
                </div>

                <div className="modal-tags">
                  <strong>标签：</strong>
                  {(modalItem.tags || []).map((tag, i) => (
                    <span key={i} className="tag">{tag}</span>
                  ))}
                  {(!modalItem.tags || modalItem.tags.length === 0) && <span className="no-tags">暂无标签</span>}
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  )
}